package svc

import (
	"errors"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
	"svcfwin/log"
)

// 查询服务状态
func QueryServiceStatus(serviceName string) (int, error) {
	log.Log.Infof("查询服务运行状态: %s", serviceName)
	cmd := exec.Command("sc", "query", serviceName)
	output, err := cmd.Output()
	if err != nil {
		return 0, err
	}
	pattern := regexp.MustCompile(`STATE\s+: (\d+)`)
	retfind := pattern.FindString(string(output))
	if retfind != "" {
		statusCode, err := strconv.Atoi(strings.TrimSpace(strings.Split(retfind, ":")[1]))
		if err != nil {
			return 0, errors.New("未知服务状态: " + retfind)
		}
		log.Log.Infof("服务运行状态: %s", retfind)
		return statusCode, nil
	}
	err = errors.New("未知服务状态")
	return 0, err
}

func QueryService(serviceName string) (string, error) {
	cmd := exec.Command("sc", "query", serviceName)
	output, err := cmd.Output()
	if err != nil {
		return "", err
	}
	return string(output), nil
}

func RestartService(serviceName string) error {
	if err := StopService(serviceName); err != nil {
		return err
	}
	if err := StartService(serviceName); err != nil {
		return err
	}
	return nil
}

func StopService(serviceName string) error {
	log.Log.Infof("执行服务终止操作: %s", serviceName)
	state, err := QueryServiceStatus(serviceName)
	if err != nil {
		return err
	}
	if state == 1 {
		log.Log.Infof("服务已停止%s,无需执行停止操作", serviceName)
		return nil
	}
	cmd := exec.Command("sc", "stop", serviceName)
	err = cmd.Run()
	if err != nil {
		return err
	}
	return nil
}

func StartService(serviceName string) error {
	log.Log.Infof("执行服务启动操作: %s", serviceName)
	state, err := QueryServiceStatus(serviceName)
	if err != nil {
		return err
	}
	if state == 4 {
		log.Log.Infof("服务已启动%s,无需执行启动操作", serviceName)
		return nil
	}
	cmd := exec.Command("sc", "start", serviceName)
	err = cmd.Run()
	if err != nil {
		return err
	}
	return nil
}
